import os
import sys
import django
import requests
from PIL import Image
import io

# 添加项目路径
sys.path.append('../backend')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'HuaXianGuan.settings')
django.setup()

from apps.flowers.models import FlowerCategory, Flower, FlowerImage

def download_and_save_image(url, filename):
    """下载并保存图片"""
    try:
        response = requests.get(url, timeout=10)
        if response.status_code == 200:
            # 保存到本地
            output_path = f"../frontend/images/flowers/{filename}"
            os.makedirs(os.path.dirname(output_path), exist_ok=True)
            
            with open(output_path, 'wb') as f:
                f.write(response.content)
            
            print(f"下载图片成功: {filename}")
            return f"/images/flowers/{filename}"
    except Exception as e:
        print(f"下载图片失败 {url}: {e}")
    return None

def create_flower_categories():
    """创建鲜花分类"""
    categories = [
        {"name": "玫瑰花", "description": "经典浪漫的玫瑰花，适合表达爱意"},
        {"name": "康乃馨", "description": "温馨的康乃馨，适合送给母亲和长辈"},
        {"name": "百合花", "description": "纯洁高雅的百合花，寓意百年好合"},
        {"name": "向日葵", "description": "阳光向上的向日葵，传递正能量"},
        {"name": "郁金香", "description": "优雅的郁金香，象征高贵与典雅"},
        {"name": "满天星", "description": "小巧精致的满天星，适合做配花"},
    ]
    
    for i, cat_data in enumerate(categories):
        category, created = FlowerCategory.objects.get_or_create(
            name=cat_data["name"],
            defaults={
                "description": cat_data["description"],
                "sort_order": i,
                "is_active": True
            }
        )
        if created:
            print(f"创建分类: {category.name}")

def create_flowers():
    """创建鲜花商品"""
    flowers_data = [
        # 玫瑰花
        {
            "name": "红玫瑰花束",
            "category": "玫瑰花",
            "description": "经典红玫瑰，11朵装，象征一心一意的爱情。新鲜采摘，花期长久。",
            "price": 168.00,
            "original_price": 198.00,
            "stock": 50,
            "is_featured": True,
        },
        {
            "name": "粉玫瑰花束",
            "category": "玫瑰花", 
            "description": "温柔粉玫瑰，19朵装，表达初恋般的美好情感。",
            "price": 228.00,
            "original_price": 268.00,
            "stock": 40,
            "is_featured": True,
        },
        {
            "name": "白玫瑰花束",
            "category": "玫瑰花",
            "description": "纯洁白玫瑰，33朵装，寓意纯真的爱情。",
            "price": 388.00,
            "original_price": 428.00,
            "stock": 30,
            "is_featured": False,
        },
        
        # 康乃馨
        {
            "name": "粉康乃馨花束",
            "category": "康乃馨",
            "description": "温馨粉康乃馨，适合送给母亲，表达感恩之情。",
            "price": 128.00,
            "original_price": 158.00,
            "stock": 60,
            "is_featured": True,
        },
        {
            "name": "红康乃馨花束",
            "category": "康乃馨",
            "description": "热情红康乃馨，表达对母亲深深的爱意。",
            "price": 138.00,
            "original_price": 168.00,
            "stock": 45,
            "is_featured": False,
        },
        
        # 百合花
        {
            "name": "白百合花束",
            "category": "百合花",
            "description": "纯洁白百合，3朵装，寓意百年好合，适合婚礼。",
            "price": 188.00,
            "original_price": 218.00,
            "stock": 35,
            "is_featured": True,
        },
        {
            "name": "粉百合花束",
            "category": "百合花",
            "description": "优雅粉百合，5朵装，温柔浪漫。",
            "price": 268.00,
            "original_price": 298.00,
            "stock": 25,
            "is_featured": False,
        },
        
        # 向日葵
        {
            "name": "向日葵花束",
            "category": "向日葵",
            "description": "阳光向日葵，9朵装，传递正能量和希望。",
            "price": 158.00,
            "original_price": 188.00,
            "stock": 40,
            "is_featured": True,
        },
        
        # 郁金香
        {
            "name": "红郁金香花束",
            "category": "郁金香",
            "description": "热情红郁金香，12朵装，象征热烈的爱情。",
            "price": 208.00,
            "original_price": 238.00,
            "stock": 30,
            "is_featured": False,
        },
        {
            "name": "粉郁金香花束",
            "category": "郁金香",
            "description": "温柔粉郁金香，15朵装，优雅浪漫。",
            "price": 248.00,
            "original_price": 278.00,
            "stock": 25,
            "is_featured": True,
        },
        
        # 满天星
        {
            "name": "满天星花束",
            "category": "满天星",
            "description": "精致满天星，纯白色，适合做配花或独立花束。",
            "price": 88.00,
            "original_price": 108.00,
            "stock": 80,
            "is_featured": False,
        },
    ]
    
    for flower_data in flowers_data:
        try:
            category = FlowerCategory.objects.get(name=flower_data["category"])
            flower, created = Flower.objects.get_or_create(
                name=flower_data["name"],
                defaults={
                    "category": category,
                    "description": flower_data["description"],
                    "price": flower_data["price"],
                    "original_price": flower_data["original_price"],
                    "stock": flower_data["stock"],
                    "is_featured": flower_data["is_featured"],
                    "status": "active",
                }
            )
            if created:
                print(f"创建鲜花: {flower.name}")
        except Exception as e:
            print(f"创建鲜花失败 {flower_data['name']}: {e}")

def create_flower_images():
    """为鲜花创建图片"""
    # 使用占位图片服务
    flowers = Flower.objects.all()
    
    for flower in flowers:
        # 检查是否已有图片
        if flower.images.exists():
            continue
            
        # 创建占位图片
        try:
            # 使用PIL创建简单的占位图片
            img = Image.new('RGB', (400, 400), color='white')
            
            # 根据鲜花类型设置背景色
            if '玫瑰' in flower.name:
                if '红' in flower.name:
                    img = Image.new('RGB', (400, 400), color='#ffebee')
                elif '粉' in flower.name:
                    img = Image.new('RGB', (400, 400), color='#fce4ec')
                else:
                    img = Image.new('RGB', (400, 400), color='#f3e5f5')
            elif '康乃馨' in flower.name:
                img = Image.new('RGB', (400, 400), color='#fff3e0')
            elif '百合' in flower.name:
                img = Image.new('RGB', (400, 400), color='#f1f8e9')
            elif '向日葵' in flower.name:
                img = Image.new('RGB', (400, 400), color='#fff8e1')
            elif '郁金香' in flower.name:
                img = Image.new('RGB', (400, 400), color='#e8f5e8')
            else:
                img = Image.new('RGB', (400, 400), color='#f5f5f5')
            
            # 保存图片
            filename = f"{flower.name.replace(' ', '_')}.jpg"
            output_path = f"../frontend/images/flowers/{filename}"
            os.makedirs(os.path.dirname(output_path), exist_ok=True)
            img.save(output_path, 'JPEG')
            
            # 创建数据库记录
            FlowerImage.objects.create(
                flower=flower,
                image_url=f"/images/flowers/{filename}",
                is_main=True,
                sort_order=0
            )
            
            print(f"创建图片: {flower.name}")
            
        except Exception as e:
            print(f"创建图片失败 {flower.name}: {e}")

def main():
    print("开始添加鲜花数据...")
    
    # 创建分类
    create_flower_categories()
    
    # 创建鲜花
    create_flowers()
    
    # 创建图片
    create_flower_images()
    
    print("鲜花数据添加完成！")
    
    # 统计信息
    print(f"总分类数: {FlowerCategory.objects.count()}")
    print(f"总鲜花数: {Flower.objects.count()}")
    print(f"总图片数: {FlowerImage.objects.count()}")

if __name__ == "__main__":
    main()